package com.netintech.process.user.controller;

import com.netintech.common.core.text.Convert;
import com.netintech.common.utils.MessageUtils;
import com.netintech.common.utils.poi.ExcelUtil;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.process.user.domain.ActIdUser;
import com.netintech.process.user.service.IActIdUserService;
import com.netintech.project.system.domain.SysUser;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程用户Controller
 *
 * @author admin
 */
@RestController
@RequestMapping("/process/user")
public class ActIdUserController extends BaseController {

    @Autowired
    private IActIdUserService actIdUserService;

    @Autowired
    private IdentityService identityService;

    /**
     * 查询流程用户列表
     */
    @PreAuthorize("@ss.hasPermi('process:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(ActIdUser actIdUser)
    {
        setPageParam();
        List<ActIdUser> list = actIdUserService.selectActIdUserList(actIdUser);
        return getDataTable(list);
    }

    /**
     * 导出流程用户列表
     */
    @Log(title = "流程用户", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('process:user:export')")
    @GetMapping("/export")
    public RequestResult export(ActIdUser actIdUser)
    {
        List<ActIdUser> list = actIdUserService.selectActIdUserList(actIdUser);
        ExcelUtil<ActIdUser> util = new ExcelUtil<>(ActIdUser.class);
        return util.exportExcel(list, "流程用户");
    }

    /**
     * 新增获取用户组信息
     */
    @GetMapping("/groups")
    public RequestResult groups()
    {
        return RequestResult.success(identityService.createGroupQuery().list());
    }

    /**
     * 新增保存流程用户
     */
    @PreAuthorize("@ss.hasPermi('process:user:add')")
    @Log(title = "流程用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public RequestResult addSave(@RequestBody ActIdUser actIdUser)
    {
        List<User> list = identityService.createUserQuery().userId(actIdUser.getId()).list();
        if (CollectionUtils.isNotEmpty(list)) {
            return RequestResult.error(MessageUtils.message("user.id.exist"));
        }
        int result = actIdUserService.insertActIdUser(actIdUser);
        String[] groupIds = actIdUser.getGroupIds();
        for (String groupId: groupIds) {
            identityService.createMembership(actIdUser.getId(), groupId);
        }
        return returnResult(result);
    }

    /**
     * 修改流程用户
     */
    @GetMapping("/edit/{id}")
    public RequestResult edit(@PathVariable("id") String id)
    {
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("actIdUser", actIdUserService.selectActIdUserById(id));
        //resultMap.put("groups", actIdUserService.selectGroupByUserId(id));
        resultMap.put("groups", identityService.createGroupQuery().groupMember(id).list());
        return RequestResult.success(resultMap);
    }

    /**
     * 修改保存流程用户
     */
    @PreAuthorize("@ss.hasPermi('process:user:edit')")
    @Log(title = "流程用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public RequestResult editSave(@RequestBody ActIdUser actIdUser)
    {
        String[] groupIds = actIdUser.getGroupIds();
        List<Group> groupList = identityService.createGroupQuery().groupMember(actIdUser.getId()).list();
        // 先删后增
        groupList.forEach(existGroup -> {
            identityService.deleteMembership(actIdUser.getId(), existGroup.getId());
        });
        int rows = actIdUserService.updateActIdUser(actIdUser);
        for (String groupId: groupIds) {
            identityService.createMembership(actIdUser.getId(), groupId);
        }
        return returnResult(rows);
    }

    /**
     * 删除流程用户
     */
    @PreAuthorize("@ss.hasPermi('process:user:remove')")
    @Log(title = "流程用户", businessType = BusinessType.DELETE)
    @DeleteMapping( "/{ids}")
    @ResponseBody
    public RequestResult remove(@PathVariable("ids") String ids)
    {
        String[] strArr = Convert.toStrArray(ids);
        for(String userId : strArr){
            List<Group> actIdGroups = identityService.createGroupQuery().groupMember(userId).list();
            if(CollectionUtils.isNotEmpty(actIdGroups)){
                return RequestResult.error(MessageUtils.message("user.ship.not.remove"));
            }
        }
        return returnResult(actIdUserService.deleteActIdUserByIds(ids));
    }

    /**
     * 系统用户列表
     * @param user
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/userList")
    @ResponseBody
    public TableDataInfo systemUserList(SysUser user) {
        setPageParam();
        List<SysUser> list = actIdUserService.selectUnAssociatedSystemUserList(user);
        return getDataTable(list);
    }

}
